<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="图片类型">
        <el-select v-model="queryParams.type" placeholder="类型" clearable size="small">
          <el-option label="请选择"
                     v-for="dict in statusOptions"
                     :key="dict.dictValue"
                     :label="dict.dictLabel"
                     :value="dict.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:img:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="imgList" @selection-change="handleSelectionChange">
      <el-table-column label="图片类型" align="center" prop="type" :formatter="statusFormat"/>
      <el-table-column label="图片" align="center" prop="url" >
        <template slot-scope="scope">
          <img :src="scope.row.url" alt="11" width="50px" height="50px" >
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:img:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:img:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px"  @close='closeDialog' >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="添加类型" prop="type">
          <el-select v-model="form.type" placeholder="添加类型" clearable size="small">
            <el-option label="请选择"
                       v-for="dict in statusOptions"
                       :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"
            >

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片地址" prop="url">
          <!--<el-input v-model="form.url" placeholder="请输入图片地址" />-->
          <!--上传图片-->
          <el-col :span="24">
            <!--<el-form-item label="上传图片">-->
            <el-upload
              class="upload-demo"
              accept="image/jpeg,image/png"
              :action="url"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleImageSuccess"
              multiple
              list-type="picture"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片格式文件</div>
            </el-upload>
            <!--</el-form-item>-->
          </el-col>

        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort"  :min="1" :max="100" ></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listImg, getImg, delImg, addImg, updateImg, exportImg,upload } from "@/api/system/img";
import { getToken } from '@/utils/auth'
export default {
  name: "Img",
  data() {
    return {
      fileList:[],
      // //上传headers
      headers:{
        'Authorization': null
      },
      //url  上传接口地址
      url:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      imgList: [],
      statusOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        url: undefined,
        sort: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "请选择图片类型", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUrl()
  },
  methods: {
    closeDialog(){
      this.fileList=[]
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listImg(this.queryParams).then(response => {
        this.imgList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getDicts("sys_img_type").then(response => {
        this.statusOptions = response.data;
      });

    },
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.type);
    },
    getUrl(){
      console.log("接口前缀", process.env.VUE_APP_BASE_API)
      //******************************************************************************
      let url =   process.env.VUE_APP_BASE_API+'/common/createOSS'
      this.url = url

      console.log("整体接口",url)
      this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    },



    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleImageSuccess(res, file, fileList) {
      // console.log(res)
      console.log(file)
      // console.log(file.raw)
      // console.log('fileList',fileList[0].response.fileName)

      // this.form.typeUrl = fileList[0].response.fileName
      this.form.url = fileList[0].response.url
      // console.log( this.form.url)

    },
    handleRemove(file, fileList) {
      this.fileList.length=0
      // this.form.typeUrl = ""
      this.form.url = ""
      // console.log( this.form)
      console.log(this.fileList)
      // console.log(file, fileList);
    },
    handlePreview(file) {

      // console.log(file);

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {

      this.form = {

        imgId: undefined,
        type: undefined,
        url: undefined,
        delFlag: undefined,
        sort: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.imgId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图片";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const imgId = row.imgId || this.ids
      getImg(imgId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改图片";


        var url = row.url
        var list =[]
        list.url  = url

        this.fileList.push( list)


      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.imgId != undefined) {
            updateImg(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addImg(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const imgIds = row.imgId || this.ids;
      this.$confirm('是否确认删除图片编号为"' + imgIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delImg(imgIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有【请填写功能名称】数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportImg(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
